import base64
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA
from Crypto.Signature import PKCS1_v1_5 as PKCS1_signature
from Crypto.Cipher import PKCS1_v1_5 as PKCS1_cipher

def get_key(key_file):
    with open(key_file) as f:
        data = f.read()
        key = RSA.importKey(data)

    return key

def rsa_private_sign(data,privateKey):
    private_key = get_key(privateKey)
    signer = PKCS1_signature.new(private_key)
    digest = SHA.new()
    digest.update(data.encode("utf8"))
    sign = signer.sign(digest)
    signature = base64.b64encode(sign)
    signature = signature.decode('utf-8')
    return signature


def rsa_public_check_sign(text, sign, publicKey):#如何知道对方的公钥？
    publick_key = get_key(publicKey)
    verifier = PKCS1_signature.new(publick_key)
    digest = SHA.new()
    digest.update(text.encode("utf8"))
    return verifier.verify(digest, base64.b64decode(sign))


def test_sign(privateKey=None, publicKey=None):
    msg = 'coolpython.net'
    sign = rsa_private_sign(msg,privateKey)
    print(rsa_public_check_sign(msg, sign,publicKey))    # True

if __name__ == '__main__':
    test_sign()